<template>
  <a-tabs type="card">
    <a-tab-pane key="private" tab="私有字段">
      <a-row :gutter="10" class="mb8">
        <a-col :span="1.5">
          <a-button
            type="primary"
            @click="handleAdd"
            v-hasPermi="['flowable:def:add']"
          >
            <template #icon><PlusOutlined /></template>
            新增
          </a-button>
        </a-col>
        <a-col :span="1.5">
          <a-button
            type="primary"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['flowable:def:edit']"
          >
            <template #icon><EditOutlined /></template>
            修改
          </a-button>
        </a-col>
        <a-col :span="1.5">
          <a-button
            type="primary"
            danger
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['flowable:def:remove']"
          >
            <template #icon><DeleteOutlined /></template>
            删除
          </a-button>
        </a-col>
      </a-row>

      <a-table
        v-loading="loading"
        :dataSource="privateFieldList"
        :rowSelection="{ selectedRowKeys: privateIds, onChange: handleSelectionPrivateChange }"
      >
        <a-table-column title="数据库字段/表单字段" dataIndex="field" align="center" />
        <a-table-column title="字段名/表单字段名" dataIndex="label" align="center" />
        <a-table-column title="字段说明" dataIndex="remark" align="center" />
        <a-table-column title="字段组件类型" dataIndex="type" align="center" />
        <a-table-column title="操作" align="center" width="180">
          <template #default="{ record }">
            <a-space>
              <a-button
                type="link"
                @click="handlePrivateUpdate(record)"
                v-hasPermi="['flowable:def:edit']"
              >
                <template #icon><EditOutlined /></template>
                修改
              </a-button>
              <a-button
                type="link"
                @click="handlePrivateDelete(record)"
                v-hasPermi="['flowable:def:remove']"
              >
                <template #icon><DeleteOutlined /></template>
                删除
              </a-button>
            </a-space>
          </template>
        </a-table-column>
      </a-table>
    </a-tab-pane>
    <a-tab-pane key="public" tab="公共字段">
      <a-row :gutter="10" class="mb8">
        <a-col :span="1.5">
          <a-button
            type="primary"
            @click="handleAdd"
            v-hasPermi="['flowable:def:add']"
          >
            <template #icon><PlusOutlined /></template>
            引用
          </a-button>
        </a-col>
        <a-col :span="1.5">
          <a-button
            type="primary"
            danger
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['flowable:def:remove']"
          >
            <template #icon><DeleteOutlined /></template>
            删除
          </a-button>
        </a-col>
      </a-row>

      <a-table
        v-loading="loading"
        :dataSource="publicFieldList"
        :rowSelection="{ selectedRowKeys: publicIds, onChange: handleSelectionPublicChange }"
      >
        <a-table-column title="数据库字段/表单字段" dataIndex="field" align="center" />
        <a-table-column title="字段名/表单字段名" dataIndex="label" align="center" />
        <a-table-column title="字段说明" dataIndex="remark" align="center" />
        <a-table-column title="字段组件类型" dataIndex="type" align="center" />
        <a-table-column title="操作" align="center" width="120">
          <template #default="{ record }">
            <a-button
              type="link"
              @click="handlePublicDelete(record)"
              v-hasPermi="['flowable:def:remove']"
            >
              <template #icon><DeleteOutlined /></template>
              删除
            </a-button>
          </template>
        </a-table-column>
      </a-table>
    </a-tab-pane>
    <a-tab-pane key="default" tab="缺省字段">
      <a-table v-loading="loading" :dataSource="defaultFieldList">
        <a-table-column title="数据库字段/表单字段" dataIndex="field" align="center" />
        <a-table-column title="字段名/表单字段名" dataIndex="label" align="center" />
        <a-table-column title="字段说明" dataIndex="remark" align="center" />
        <a-table-column title="字段组件类型" dataIndex="type" align="center" />
      </a-table>
    </a-tab-pane>
  </a-tabs>

  <a-modal
    :title="field.title"
    v-model:open="field.open"
    width="70%"
    @ok="submitForm"
    @cancel="cancel"
  >
    <a-scrollbar>
      <a-form
        ref="formRef"
        :model="formData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        :rules="rules"
      >
        <a-divider orientation="left">基本信息</a-divider>
        <a-form-item
          name="field"
          label="字段"
          :rules="[{ pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '必须以字母或下划线开头' }]"
        >
          <a-input v-model:value="formData.field" />
        </a-form-item>
        <a-form-item name="label" label="标签" :rules="[{ required: true }]">
          <a-input v-model:value="formData.label" />
        </a-form-item>
        <a-form-item name="remark" label="说明">
          <a-input v-model:value="formData.remark" />
        </a-form-item>
        <a-form-item name="width" label="宽度" :rules="[{ required: true }]">
          <a-input-number v-model:value="formData.width" :min="1" style="width: 100%" />
        </a-form-item>
        <a-form-item name="type" label="类型" :rules="[{ required: true }]">
          <a-select
            v-model:value="formData.type"
            @change="v => formData.scheme.type = v"
            style="width: 100%"
          >
            <a-select-option value="number">数字</a-select-option>
            <a-select-option value="text">文本</a-select-option>
            <a-select-option value="option">选项</a-select-option>
            <a-select-option value="user">用户</a-select-option>
            <a-select-option value="dept">部门</a-select-option>
            <a-select-option value="date">时间</a-select-option>
            <a-select-option value="daterange">时间范围</a-select-option>
          </a-select>
        </a-form-item>
        <a-divider orientation="left">组件配置</a-divider>
        <component :form-data="formData" :is="schemeConfigComponentMap[formData.type]" />
      </a-form>
    </a-scrollbar>
  </a-modal>
</template>

<script setup>
import { markRaw, ref, watch } from "vue";
import * as refApi from "@/api/business/flowable/ref";
import { listAll } from "@/api/business/flowable/def";
import NumberSchemeConfig from "@/views/modeling/field/form/NumberSchemeConfig.vue";
import TextSchemeConfig from "@/views/modeling/field/form/TextSchemeConfig.vue";
import OptionSchemeConfig from "@/views/modeling/field/form/OptionSchemeConfig.vue";
import UserSchemeConfig from "@/views/modeling/field/form/UserSchemeConfig.vue";
import DeptSchemeConfig from "@/views/modeling/field/form/DeptSchemeConfig.vue";
import DateSchemeConfig from "@/views/modeling/field/form/DateSchemeConfig.vue";
import DateRangeSchemeConfig from "@/views/modeling/field/form/DateRangeSchemeConfig.vue";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue';
import { message, Modal } from 'ant-design-vue';

const props = defineProps({
  mkey: String,
  version: String
});

const loading = ref(false);
const privateFieldList = ref([]); // 私有字段列表
const publicFieldList = ref([]); // 公共字段列表
const defaultFieldList = ref([]); // 缺省字段列表
const privateIds = ref([]);
const privateSingle = ref(true);
const privateMultiple = ref(true);
const publicIds = ref([]);
const publicSingle = ref(true);
const publicMultiple = ref(true);

const schemeConfigComponentMap = ref({
  number: markRaw(NumberSchemeConfig),
  text: markRaw(TextSchemeConfig),
  option: markRaw(OptionSchemeConfig),
  user: markRaw(UserSchemeConfig),
  dept: markRaw(DeptSchemeConfig),
  date: markRaw(DateSchemeConfig),
  daterange: markRaw(DateRangeSchemeConfig),
});

const formData = ref({
  mkey: '',
  field: '',
  label: '',
  remark: '',
  width: 16,
  type: 'number',
  scope: '',
  scheme: {
    type: 'number'
  }
});

const field = ref({
  title: '',
  open: false
});

const rules = {
  field: [{ required: true, message: '请输入字段' }],
  label: [{ required: true, message: '请输入标签' }],
  width: [{ required: true, message: '请输入宽度' }],
  type: [{ required: true, message: '请选择类型' }]
};

watch(
  () => [props.mkey, props.version],
  (newVal) => {
    loading.value = true;
    // 缺省字段列表为空,才查
    if (defaultFieldList.value.length === 0) {
      const queryParams1 = { module: 'WORKFLOW', scope: 'WORKFLOW_DEFAULT' };
      listAll(queryParams1).then(response => {
        defaultFieldList.value = response.data;
      });
    }
    if (newVal[0] && newVal[1]) {
      // 查询私有的字段
      const queryParams = {
        module: 'WORKFLOW',
        mkey: newVal[0],
        version: newVal[1],
        scope: 'WORKFLOW_PRIVATE'
      };
      refApi.listCombination(queryParams)
        .then(response => {
          privateFieldList.value = response.data;
        });

      // 查询公共字段
      const publicQueryParams = {
        module: 'WORKFLOW',
        mkey: newVal[0],
        version: newVal[1],
        scope: 'GLOBAL'
      };
      refApi.listCombination(publicQueryParams)
        .then(response => {
          publicFieldList.value = response.data;
        })
        .finally(() => {
          loading.value = false;
        });
    } else {
      loading.value = false;
    }
  },
  {
    immediate: true,
  }
);

// 多选框选中数据
function handleSelectionPrivateChange(selectedRowKeys) {
  privateIds.value = selectedRowKeys;
  privateSingle.value = selectedRowKeys.length !== 1;
  privateMultiple.value = !selectedRowKeys.length;
}

function handleSelectionPublicChange(selectedRowKeys) {
  publicIds.value = selectedRowKeys;
  publicSingle.value = selectedRowKeys.length !== 1;
  publicMultiple.value = !selectedRowKeys.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  field.value.open = true;
  field.value.title = "添加流程字段定义";
}

/** 修改按钮操作 */
function handleUpdate() {
  reset();
  const _id = privateIds.value[0];
  getDef(_id).then(response => {
    formData.value = response.data;
    field.value.open = true;
    field.value.title = "修改流程字段定义";
  });
}

/** 提交按钮 */
function submitForm() {
  formRef.value.validate().then(() => {
    if (formData.value.id) {
      updateDef(formData.value).then(() => {
        message.success("修改成功");
        field.value.open = false;
        getList();
      });
    } else {
      addDef(formData.value).then(() => {
        message.success("新增成功");
        field.value.open = false;
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete() {
  const _ids = privateIds.value;
  Modal.confirm({
    title: '确认',
    content: `是否确认删除流程字段定义编号为"${_ids}"的数据项？`,
    onOk() {
      return delDef(_ids).then(() => {
        getList();
        message.success("删除成功");
      });
    }
  });
}

function handlePrivateDelete(record) {
  Modal.confirm({
    title: '确认',
    content: `是否确认删除该字段？`,
    onOk() {
      return delDef(record.id).then(() => {
        getList();
        message.success("删除成功");
      });
    }
  });
}

function handlePublicDelete(record) {
  Modal.confirm({
    title: '确认',
    content: `是否确认删除该字段？`,
    onOk() {
      return delDef(record.id).then(() => {
        getList();
        message.success("删除成功");
      });
    }
  });
}

function reset() {
  formData.value = {
    mkey: '',
    field: '',
    label: '',
    remark: '',
    width: 16,
    type: 'number',
    scope: '',
    scheme: {
      type: 'number'
    }
  };
}

const formRef = ref(null);
</script>

<style scoped>
.mb8 {
  margin-bottom: 8px;
}
</style>
